import { BASE_URL, HEADER_CONTENT } from '@/config/constant/index'
import { getLocalToken } from '@/util/token'
import { queryString } from '@/util/queryString'
import type { Result } from '@/config/data/data'

/**
 * 请求前置函数
 * @param mode 请求的模式
 */
const beforeRequest = (mode: string) => {
  try {
    // console.log('beforeRequest', mode)
  } catch (err) {
    console.error('beforeRequest error', err)
  }
}

// 请求后置函数
const afterRequest = (code: number = 200, msg: string = '') => {
  if (code != 200) {
    uni.showToast({
      title: msg,
      icon: 'none',
      mask: true,
      duration: 500,
    })
  }
}

/**
 * 普通get请求 Result风格
 * @param apiUrl 请求的api地址
 * @param query 拼接在请求路径后的参数，可选
 */
export const getResult = async <T>(
  apiUrl: string,
  query: string | number,
): Promise<Result<T>> => {
  await beforeRequest('base')

  try {
    const res = await uni.request({
      url: BASE_URL + apiUrl + '/' + query,
      method: 'GET',
      header: {
        'Content-Typ': HEADER_CONTENT.JSON,
        token: getLocalToken(),
      },
    })
    //响应对象
    let r = res.data as Result<T>
    afterRequest(r.code, r.msg)
    return r
  } catch (err) {
    afterRequest(404, '服务器连接异常')
    console.error(`${apiUrl} get error`, err)
    throw err
  }
}

/**
 * 普通get请求
 * @param apiUrl 请求的api地址
 * @param query 拼接在请求路径后的参数，可选
 */
export const get = async <T>(
  apiUrl: string,
  query: AnyObject = {}
): Promise<Result<T>> => {
  //取消请求控制器

  try {
    const res = await uni.request({
      url: BASE_URL + apiUrl + queryString(query),
      method: 'GET',
      header: {
        'Content-Type': HEADER_CONTENT.JSON,
        token: getLocalToken(),
      },
    })

    //响应对象
    let r = res.data as Result<T>
    afterRequest(r.code, r.msg)
    return r
  } catch (err: any) {
    afterRequest(404, '服务器连接异常')
    console.error(`${apiUrl} get error`, err)
    throw err
  }
}

/**
 * 普通post请求
 * @param apiUrl 请求的api地址
 * @param data 请求的参数，可选
 */
export const post = async <T>(
  apiUrl: string,
  data: AnyObject
): Promise<Result<T>> => {
  // await beforeRequest('base')

  try {
    const res = await uni.request({
      url: BASE_URL + apiUrl,
      method: 'POST',
      header: {
        'Content-Type': HEADER_CONTENT.JSON,
        token: getLocalToken(),
      },
      data,
    })
    //响应对象
    let r = res.data as Result<T>
    afterRequest(r.code, r.msg)
    return r
  } catch (err) {
    afterRequest(404, '服务器连接异常')
    console.error(`${apiUrl} post error`, err)
    throw err
  }
}

/**
 * 上传文件
 * @param apiUrl 请求的api地址
 * @param filePath 请求的文件路径
 * @param formData 请求的其他参数，可选
 */
export const uploadFile = async <T>(
  apiUrl: string,
  filePath?: string,
  formData?: AnyObject
): Promise<Result<T>> => {
  try {
    const res = await new Promise((resolve): any => {
      uni.uploadFile({
        method: 'POST',
        url: BASE_URL + apiUrl,
        filePath,
        header: {
          'Content-Type': HEADER_CONTENT.FILE,
          token: getLocalToken(),
        },
        name: 'image_file',
        formData: {
          ...formData,
        },
        success: (successRes) => {
          resolve(JSON.parse(successRes.data))
        },
        fail: (err) => {
          throw err
        },
        complete: () => {},
      })
    })
    //响应对象
    let r = res as Result<T>
    afterRequest(r.code, r.msg)
    return r
  } catch (err) {
    afterRequest(404, '服务器连接异常')
    console.error(`${apiUrl} uploadFile error`, err)
    throw err
  }
}
